<?php

declare(strict_types=1);

namespace app\order\controller;

use app\cart\model\GoodsShopcar;
use app\order\model\OrderGoods;
use app\CheckTokenController;
use app\order\model\Order;

class Save extends CheckTokenController
{
    /**
     * 生成订单号的函数
     *
     * @return int  订单号
     */
    protected function GenerateOrderNumber()
    {
        $order_sn = date('Ymd') . substr(implode('', array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
        return $order_sn;
    }
    // 存储订单信息的函数
    public function index()
    {

        $params = $this->request->param();
        $DBOrderGoods = new OrderGoods();
        $DBOrder = new Order();
        $DBCart = new GoodsShopcar();
        $orderSn = $this->GenerateOrderNumber();
        $list = [];
        foreach ($params['orderList'] as $key => $value) {
            array_push($list, ['order_id' => $orderSn, 'goods_id' => $value['goods_id'], 'goods_num' => $value['number'], 'goods_price' => $value['goods_price']]);
        }
        // 存储订单商品表
        $info = $DBOrderGoods->saveAll($list);

        // 存储用户订单信息表
        $DBOrder->order_id = $orderSn;
        $DBOrder->total_price = $params['totalPrice'];
        $DBOrder->uid = $params['uid'];
        $DBOrder->is_pay = 1;
        $DBOrder->save();
        if ($info) {
            // 然后删除购物车商品
            foreach ($params['orderList'] as $key => $value) {
                $DBCart->where('uid', $params['uid'])->where('goods_id', $value['goods_id'])->delete();
            }
            return result($orderSn, '订单提交成功！');
        }
    }
}